package com.pingguopifa.interceptor;

import java.io.IOException;
import java.io.StringWriter;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.Ostermiller.util.CSVPrinter;
import com.pingguopifa.interceptor.LoggerService;
import com.pingguopifa.utils.DateFormatter;

public class AuditTrailInterceptor extends HandlerInterceptorAdapter {

	private static final DateFormatter DATE_FORMATTER = new DateFormatter();
	private static final Logger LOGGER = Logger.getLogger(AuditTrailInterceptor.class);
	private LoggerService loggerService;
 
	@SuppressWarnings("rawtypes")
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		Date now = new Date();
		StringWriter writer = new StringWriter();
		CSVPrinter printer = new CSVPrinter(writer);
		printer.changeDelimiter(LoggerService.AUDIT_TRAIL_DELIMITER);
		printer.setAlwaysQuote(true);
		try {
			printer.write("requestTime:" + DATE_FORMATTER.format(now));
			printer.write("requesturl:" + request.getRequestURL());
			Iterator it = request.getParameterMap().entrySet().iterator();
			while (it.hasNext()) {
				Map.Entry m = (Map.Entry) it.next();
				String[] values = (String[]) m.getValue();
				for (String value : values) {
					printer.write(m.getKey() + ":" + value);
				}
			}
			printer.println();
			loggerService.info(writer.toString());
		} catch (IOException e) {
			LOGGER.info("log audit failed, error !!!", e);
		} finally {
			try {
				writer.close();
				printer.close();
			} catch (IOException e) {
				LOGGER.info(e);
			}
		}
		return super.preHandle(request, response, handler);
	}
	
	public void setLoggerService(LoggerService loggerService) {
		this.loggerService = loggerService;
	}
}
